import { useAppDispatch, useAppSelector } from '../../../../store/hooks'
import { selectSearch } from '../../../../store/reducers/selectors'
import { ChangeEvent, useEffect, useState } from 'react'
import { alpha, styled } from '@mui/material'
import SearchIcon from '@mui/icons-material/Search'
import InputBase from '@mui/material/InputBase'
import { catalogSlice } from '../../../../store/reducers/slices/catalogSlice'
import { searchSlice } from '../../../../store/reducers/slices/searchSlice'

const SearchIconWrapper = styled('div')(({ theme }) => ({
	color: theme.palette.common.black,
	padding: theme.spacing(0, 2),
	height: '100%',
	position: 'static',
	pointerEvents: 'none',
	display: 'flex',
	alignItems: 'center',
	justifyContent: 'center',
}))
const StyledSearch = styled('div')(({ theme }) => ({
	width: '468px',
	height: '24px',
	background: 'rgb(255, 255, 255)',
	borderRadius: '24px',
	display: 'flex',
	flexDirection: 'row',
	alignItems: 'center',
	padding: '12px 20px 12px 20px',
	margin: '0px 80px',
	'&:hover': {
		backgroundColor: alpha(theme.palette.common.black, 0.25),
	},
}))

const StyledInputBase = styled(InputBase)(({ theme }) => ({
	color: theme.palette.common.black,
	width: '100%',
	'& .MuiInputBase-input': {
		padding: theme.spacing(1, 1, 1, 0),
		paddingLeft: `calc(1em + ${theme.spacing(4)})`,
		transition: theme.transitions.create('width'),
		[theme.breakpoints.up('sm')]: {
			width: '12ch',
			'&:focus': {
				width: '20ch',
			},
		},
	},
}))

const Search = () => {
	const search = useAppSelector(selectSearch)
	const dispatch = useAppDispatch()
	const [searchCurrent, setSearch] = useState(search)

	useEffect(() => {
		dispatch(catalogSlice.actions.setPage(1))
		dispatch(searchSlice.actions.setSearch(searchCurrent))
	}, [dispatch, searchCurrent, search])

	function handleChange(event: ChangeEvent<HTMLInputElement>) {
		setSearch(event.target.value)
	}

	return (
		<StyledSearch>
			<SearchIconWrapper>
				<SearchIcon />
			</SearchIconWrapper>
			<StyledInputBase
				placeholder='Поиск'
				value={searchCurrent}
				onChange={handleChange}
			/>
		</StyledSearch>
	)
}

export default Search
